﻿using System;
using System.Collections;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.IO;
using System.Drawing.Imaging;
using System.Drawing;

namespace Card.Web.ImageService
{
    /// <summary>
    /// $codebehindclassname$ 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class ImageService : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            string action = context.Request.QueryString["a"].ToUpper();
            switch (action)
            {
                case "W"://得到文字图片
                    this.CreateImage(context);
                    break;
                case "AW"://admin添加图片
                    this.CreateAdminImage(context);
                    break;
                case "CT"://创建模版缩略图
                    this.CreateTemplateThumbnail(context);
                    break;
                case "SU":
                    this.SaveUserCard(context);
                    break;
                case "DU":
                    this.DeleteUserCard(context);
                    break;
                case "CO":
                    this.CreateOrderCard(context);
                    break;
                case "DOC":
                    this.DeleteOrderCardFiles(context);
                    break;
                default:
                    break;
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        private void CreateImage(HttpContext context)
        {
            string word,fontColor,fontSize,fontFamliy,fontStyle=string.Empty;
            word = context.Request.QueryString["w"].ToString();
            if (context.Request.QueryString["e"] != null && string.Compare(context.Request.QueryString["e"], CONST.YES_NO.YES,true) == 0)
            {
                word = Card.Utility.TextUtility.JSUnescape(word);
            }
            if (context.Request.QueryString["lstfi"] != null && string.Compare(context.Request.QueryString["lstfi"], CONST.YES_NO.YES, true) == 0)
            {
                string[] fontInfo = Card.Utility.TextUtility.JSUnescape(context.Request.QueryString["f"]).Split('|');
                fontColor = fontInfo[0];
                fontSize = fontInfo[1];
                fontFamliy = fontInfo[2];                
            }
            else
            {
                fontColor = "#" + context.Request.QueryString["fc"];
                fontSize = context.Request.QueryString["fs"];
                fontFamliy = Card.Utility.TextUtility.JSUnescape(context.Request.QueryString["ff"]);
                fontStyle = context.Request.QueryString["fst"];
            }

            Font font = Helper.ImageHelper.GetFont(fontFamliy, float.Parse(fontSize), fontStyle);

            Color color = Color.Black;
            try
            {
                color = ColorTranslator.FromHtml(fontColor);
            }
            catch (Exception ex)
            {
                Log.Logger.Error(ex.ToString());
                color = Color.Black;
            }

            Bitmap img = Utility.ImageUtilty.CreateImage(word, font, color);

            byte[] buffer;
            using (MemoryStream ms = new MemoryStream())
            {
                img.Save(ms, ImageFormat.Png);
                ms.Position = 0;
                buffer = new byte[ms.Length];
                ms.Read(buffer, 0, Convert.ToInt32(ms.Length));
                ms.Flush();
            }

            context.Response.ContentType = "image/png;";           
            context.Response.BinaryWrite(buffer);
        }

        private void CreateAdminImage(HttpContext context)
        {
            string word = context.Request.QueryString["w"].ToString();
            if (context.Request.QueryString["e"] != null && string.Compare(context.Request.QueryString["e"], CONST.YES_NO.YES) == 0)
            {
                word = Card.Utility.TextUtility.JSUnescape(word);
            }
            string fontFamily = context.Request.QueryString["ff"].ToString();
            string fontSize = context.Request.QueryString["fs"].ToString();
            string strColor = string.IsNullOrEmpty(context.Request.QueryString["c"]) ? "#000000" : "#" + Card.Utility.TextUtility.JSUnescape(context.Request.QueryString["c"].ToString());
            string fontStyle = string.Empty;
            Color color = Color.Black;
            try
            {
                color = ColorTranslator.FromHtml(strColor);
            }
            catch (Exception ex)
            {
                Log.Logger.Error(ex.ToString());
            }

            Font font = Helper.ImageHelper.GetFont(fontFamily, float.Parse(fontSize), fontStyle);

            Bitmap img = Utility.ImageUtilty.CreateImage(word, font, color);

            byte[] buffer;
            using (MemoryStream ms = new MemoryStream())
            {
                img.Save(ms, ImageFormat.Png);
                ms.Position = 0;
                buffer = new byte[ms.Length];
                ms.Read(buffer, 0, Convert.ToInt32(ms.Length));
                ms.Flush();
            }

            context.Response.ContentType = "image/png;";
            context.Response.BinaryWrite(buffer);
        }

        private void CreateTemplateThumbnail(HttpContext context)
        {
            string result = string.Empty;

            try
            {
                #region
                int cardID = int.Parse(context.Request.QueryString["id"]);
                Entity.Template card = BLL.TemplateManager.GetEntity(cardID, null);
                Entity.TemplateLogo logo = BLL.TemplateLogoManager.GetEntity(cardID, CONST.CARD_FACE_TYPE.FRONT, null);
                DataTable frontFields = BLL.TemplateFieldManager.GetFieldList(cardID, CONST.CARD_FACE_TYPE.FRONT, null);

                if (card != null && !string.IsNullOrEmpty(card.FrontImage))
                {
                    string folder = context.Server.MapPath(string.Format("TemplateImages/{0}/{1}/", card.FrontImage.Substring(0, 4), card.FrontImage.Substring(4, 2)));
                    string suffix = card.FrontImage.Substring(card.FrontImage.LastIndexOf('.')).ToLower().TrimStart('.');
                    string fullFileName = string.Format("{0}{1}", folder, card.FrontImage.Replace(".", "TM."));

                    Image frontImg = Image.FromFile(string.Format("{0}{1}", folder, card.FrontImage), false);
                    double scale = 1;
                    if (frontImg.Width > frontImg.Height)
                    {
                        scale = frontImg.Width / 400.0;
                    }
                    else
                    {
                        scale = frontImg.Width / 240.0;
                    }

                    Graphics g = Graphics.FromImage(frontImg);

                    if (logo != null)
                    {
                        Image logoImg = Image.FromFile(context.Server.MapPath(string.Format("logoImages/{0}", logo.Logo)));
                        int posX = (int)(decimal.ToDouble(logo.PosX) * scale);
                        int posY = (int)(decimal.ToDouble(logo.PosY) * scale);
                        int width = (int)(decimal.ToDouble(logo.Width) * scale);
                        int height = (int)(decimal.ToDouble(logo.Height) * scale);

                        g.DrawImage(logoImg, posX, posY, width, height);
                    }

                    foreach (DataRow row in frontFields.Rows)
                    {
                        Font font = Helper.ImageHelper.GetFont(row["FONT_FAMILY"].ToString(), (float)(float.Parse(row["FONT_SIZE"].ToString()) * scale),row["FONT_STYLE"].ToString());
                        Color color = Color.Black;
                        try
                        {
                            color = ColorTranslator.FromHtml(row["COLOR"].ToString());
                        }
                        catch (Exception ex)
                        { }

                        int posX = (int)(double.Parse(row["POS_X"].ToString()) * scale);
                        int posY = (int)(double.Parse(row["POS_Y"].ToString()) * scale);

                        if (string.Compare(CONST.FIELD_DIRECTION.LEFT, row["DIRECTION"].ToString(), true) == 0)
                        {
                            Bitmap wordImg = Utility.ImageUtilty.CreateImage(row["CONTENT"].ToString(), font, color);
                            posX = posX - wordImg.Width;
                            wordImg.Dispose();
                        }

                        g.DrawString(row["CONTENT"].ToString(), font, new SolidBrush(color), posX, posY, StringFormat.GenericTypographic);
                    }

                    if (frontImg.Width > frontImg.Height)
                    {
                        Helper.ImageHelper.ToThumbnail(frontImg, fullFileName, suffix, 240, 120, false);
                    }
                    else
                    {
                        Helper.ImageHelper.ToThumbnail(frontImg, fullFileName, suffix, 72, 120, false);
                    }

                    g.Dispose();
                    frontImg.Dispose();

                    result = string.Format("{{'r':'y','msg':'success','img':'{0}'}}", card.FrontImage.Replace(".", "TM."));
                }
                else
                {
                    result = "{'r':'n','msg':'模版不存在或者还没有上传图片！'}";
                }
                #endregion
            }
            catch (Exception ex)
            {
                result = string.Format("{{'r':'n','msg':'{0}'}}", ex.Message);
            }


            context.Response.ContentType = "text/plain";
            context.Response.Write(result);
        }

        private void SaveUserCard(HttpContext context)
        {
            string result = string.Empty;

            try
            {

                int cardID = int.Parse(context.Request.QueryString["id"]);
                Entity.UserCard card = BLL.UserCardManager.GetEntity(cardID, null);
                Card.Security.Passport passport = Card.Security.CookieManager.GetPassport();
                if (passport.UserID == card.UserID)
                {
                    this.SvarUserCard(context, card, CONST.CARD_FACE_TYPE.FRONT, passport);
                    this.SvarUserCard(context, card, CONST.CARD_FACE_TYPE.BACK, passport);
                    result = "{'r':'y'}";
                }
                else
                {
                    result = "{'r':'n','msg':'没有权限！'}";
                }

            }
            catch (Exception ex)
            {
                result = string.Format("{{'r':'n','msg':'{0}'}}", ex.Message);
            }


            context.Response.ContentType = "text/plain";
            context.Response.Write(result);

        }

        private void SvarUserCard(HttpContext context, Entity.UserCard card, string faceType, Card.Security.Passport passport)
        {
            string strFaceImage = string.Compare(faceType, CONST.CARD_FACE_TYPE.FRONT, true) == 0 ? card.FrontImage : card.BackImage;
            Entity.UserCardLogo logo = BLL.UserCardLogoManager.GetEntity(card.ID, faceType, null);
            DataTable fields = BLL.UserCardFieldManager.GetFieldList(card.ID, faceType, null);

            if (card != null && !string.IsNullOrEmpty(card.FrontImage))
            {
                string folder = context.Server.MapPath(string.Format("UserCards/{0}/{1}/", passport.UserID, card.ID));
                string suffix = strFaceImage.Substring(strFaceImage.LastIndexOf('.')).ToLower().TrimStart('.');
                string fullFileName = string.Format("{0}{1}.{2}", folder, faceType, suffix);
                string fullThumFileName = string.Format("{0}{1}T.{2}", folder, faceType, suffix);

                if (!Directory.Exists(folder))
                {
                    Directory.CreateDirectory(folder);
                }

                Image faceImage = Image.FromFile(Helper.ImageHelper.GetTemplateImageFullName(strFaceImage), false);
                double scale = 1;
                if (faceImage.Width > faceImage.Height)
                {
                    scale = faceImage.Width / 400.0;
                }
                else
                {
                    scale = faceImage.Width / 240.0;
                }

                Graphics g = Graphics.FromImage(faceImage);
                
                if (logo != null && !logo.IsHidden)
                {
                    Image logoImg = Image.FromFile(context.Server.MapPath(string.Format("logoImages/{0}", logo.Logo)));
                    int posX = (int)(decimal.ToDouble(logo.PosX) * scale);
                    int posY = (int)(decimal.ToDouble(logo.PosY) * scale);
                    int width = (int)(decimal.ToDouble(logo.Width) * scale);
                    int height = (int)(decimal.ToDouble(logo.Height) * scale);

                    g.DrawImage(logoImg, posX, posY, width, height);
                }

                foreach (DataRow row in fields.Rows)
                {
                    Font font = Helper.ImageHelper.GetFont(row["FONT_FAMILY"].ToString(), (float)(float.Parse(row["FONT_SIZE"].ToString()) * scale),row["FONT_STYLE"].ToString());
                    Color color = Color.Black;
                    try
                    {
                        color = ColorTranslator.FromHtml(row["COLOR"].ToString());
                    }
                    catch (Exception ex)
                    { }

                    int posX = (int)(double.Parse(row["POS_X"].ToString()) * scale);
                    int posY = (int)(double.Parse(row["POS_Y"].ToString()) * scale);

                    if (string.Compare(CONST.FIELD_DIRECTION.LEFT, row["DIRECTION"].ToString(), true) == 0)
                    {
                        Bitmap wordImg = Utility.ImageUtilty.CreateImage(row["CONTENT"].ToString(), font, color);
                        posX = posX - wordImg.Width;
                        wordImg.Dispose();
                    }

                    g.DrawString(row["CONTENT"].ToString(), font, new SolidBrush(color), posX, posY, StringFormat.GenericTypographic);
                }

                if (faceImage.Width < faceImage.Height)
                {
                    Helper.ImageHelper.ToThumbnail(faceImage, fullThumFileName, suffix, 240, 400, false);
                }
                else
                {
                    Helper.ImageHelper.ToThumbnail(faceImage, fullThumFileName, suffix, 400, 240, false);
                }

                if (string.Compare(faceType, CONST.CARD_FACE_TYPE.FRONT, true) == 0)
                {
                    string strListFileName = string.Format("{0}TL.{1}", folder, suffix);
                    if (faceImage.Width > faceImage.Height)
                    {
                        Helper.ImageHelper.ToThumbnail(faceImage, strListFileName, suffix, 240, 120, false);
                    }
                    else
                    {
                        Helper.ImageHelper.ToThumbnail(faceImage, strListFileName, suffix, 72, 240, false);
                    }
                }

                if (File.Exists(fullFileName))
                {
                    File.Delete(fullFileName);
                }

                
                //faceImage.Save(fullFileName);
                Bitmap bitFaceImage = new Bitmap(faceImage);
                bitFaceImage.SetResolution(310, 310);
                bitFaceImage.Save(fullFileName);
                g.Dispose();
                faceImage.Dispose();
                bitFaceImage.Dispose();
            }
            else
            {
                throw new Exception("模版不存在！");
            }
        }
        /// <summary>
        /// 删除用户图片
        /// </summary>
        /// <param name="context"></param>
        private void DeleteUserCard(HttpContext context)
        {
            string result = string.Empty;

            try
            {
                Card.Security.Passport passport = Card.Security.CookieManager.GetPassport();
                int cardID = int.Parse(context.Request.QueryString["id"]);
                string folder = context.Server.MapPath(string.Format("UserCards/{0}/{1}", passport.UserID, cardID));
                if (Directory.Exists(folder))
                {
                    Directory.Delete(folder, true);
                }
                result = "{'r':'y'}";
            }
            catch (Exception ex)
            {
                result = string.Format("{{'r':'n','msg':'{0}'}}", ex.Message);
            }


            context.Response.ContentType = "text/plain";
            context.Response.Write(result);
        }
        /// <summary>
        /// copy生成Order Card文件
        /// </summary>
        /// <param name="context"></param>
        private void CreateOrderCard(HttpContext context)
        {
            string result = string.Empty;

            try
            {
                Card.Security.Passport passport = Card.Security.CookieManager.GetPassport();
                int cardID = int.Parse(context.Request.QueryString["cid"]);
                int orderCardID = int.Parse(context.Request.QueryString["oid"]);
                int userID = int.Parse(context.Request.QueryString["uid"]);
                if (passport.UserID == userID)
                {
                    string folder = context.Server.MapPath(string.Format("UserCards/{0}/{1}", userID, cardID));
                    string orderFolder = context.Server.MapPath(string.Format("OrderCards/{0}/{1}/", userID, orderCardID));
                    if (Directory.Exists(folder))
                    {
                        if (!Directory.Exists(orderFolder))
                        {
                            Directory.CreateDirectory(orderFolder);
                        }

                        FileInfo[] files = new DirectoryInfo(folder).GetFiles();
                        foreach (FileInfo file in files)
                        {
                            file.CopyTo(string.Format("{0}{1}", orderFolder, file.Name), true);
                        }
                        result = "{'r':'y'}";
                    }
                    else
                    {
                        result = "{'r':'n','msg':'没有权限'}";
                    }

                }

            }
            catch (Exception ex)
            {
                Log.Logger.Error(ex.ToString());
                result = string.Format("{{'r':'n','msg':'{0}'}}", ex.Message);
            }


            context.Response.ContentType = "text/plain";
            context.Response.Write(result);
        }
        /// <summary>
        /// 删除订单名片文件
        /// </summary>
        /// <param name="context"></param>
        private void DeleteOrderCardFiles(HttpContext context)
        {
            string result = string.Empty;
            try
            {
                Card.Security.Passport passport = Card.Security.CookieManager.GetPassport();
                int orderCardID = int.Parse(context.Request.QueryString["id"]);
                int userID = int.Parse(context.Request.QueryString["uid"]);
                if (passport.UserID == userID)
                {
                    string orderFolder = context.Server.MapPath(string.Format("OrderCards/{0}/{1}/", userID, orderCardID));
                    if (Directory.Exists(orderFolder))
                    {
                        Directory.Delete(orderFolder, true);
                    }
                    result = "{'r':'y'}";
                }
                else
                {
                    result = "{'r':'n','msg':'没有权限'}";
                }
            }
            catch (Exception ex)
            {
                Log.Logger.Error(ex.ToString());
                result = string.Format("{{'r':'n','msg':'{0}'}}", ex.Message);
            }

            context.Response.ContentType = "text/plain";
            context.Response.Write(result);
        }
    }
}
